<template>
  <div class="login-container">
    <el-card class="login-card">
      <h1 class="login-title">Login</h1>
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="80px" @keyup.enter="login" >
        <el-form-item label="Username" prop="username">
          <el-input v-model="form.username" placeholder="Username" clearable></el-input>
        </el-form-item>
        <el-form-item label="Password" prop="password">
          <el-input type="password" v-model="form.password" placeholder="Password" show-password clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.rememberMe">Remember Me</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" class="login-button">Login</el-button>
        </el-form-item>
        <div class="register-link">
        Don't have an account? <router-link to="/register">Register</router-link>
      </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const form = ref({
  username: '',
  password: '',
  rememberMe: false
})

const rules = ref({
  username: [
    { required: true, message: 'Please input username', trigger: 'blur' },
    { min: 6, message: 'Username must be at least 6 characters', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: 'Username can only contain letters and numbers', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' },
    { min: 8, message: 'Password must be at least 8 characters', trigger: 'blur' }
  ]
})

const loginForm = ref(null)
const router = useRouter()
const authStore = useAuthStore()

// Utility functions for localStorage
const storageKey = 'userCredentials'

const saveCredentials = (username, password, rememberMe) => {
  const data = JSON.stringify({ username, password, rememberMe })
  localStorage.setItem(storageKey, btoa(data))
}

const loadCredentials = () => {
  const data = localStorage.getItem(storageKey)
  if (data) {
    try {
      return JSON.parse(atob(data))
    } catch (e) {
      console.error('Failed to parse stored credentials', e)
      return null
    }
  }
  return null
}

const clearCredentials = () => {
  localStorage.removeItem(storageKey)
}

const login = () => {
  loginForm.value.validate(async (valid) => {
    if (valid) {
      const response = await authStore.login(form.value.username, form.value.password)
      if (response.success) {
        // console.log(authStore.user)
        if (form.value.rememberMe) {
          saveCredentials(form.value.username, form.value.password, form.value.rememberMe)
        } else {
          clearCredentials()
        }
        ElMessage.success(response.message)
        router.push('/')
      } else {
        ElMessage.error(response.message)
      }
    } else {
      ElMessage.error('Please fill the form correctly')
    }
  })
}

onMounted(() => {

  const tempRegisterInfo = authStore.tempRegisterInfo
  if(tempRegisterInfo){
     // 使用临时注册信息填充表单
    form.value.username = tempRegisterInfo.username
    form.value.password = tempRegisterInfo.password
    // 清除临时注册信息
    authStore.clearTempRegisterInfo()
    // 清除之前保存的凭据
    clearCredentials()
  }else{
     // 如果没有临时注册信息，则尝试加载保存的凭据
      const credentials = loadCredentials()
      if (credentials) {
        form.value.username = credentials.username
        form.value.password = credentials.password
        form.value.rememberMe = credentials.rememberMe
      }
  }

})
</script>


<style scoped>
.login-container {
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% {
    background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  }
  50% {
    background: linear-gradient(to right, #2575fc 0%, #6a11cb 100%);
  }
  100% {
    background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  }
}

.login-card {
  width: 400px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  transition: all 0.3s;
  background-color: #fff;
}

.login-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.2);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}

.el-input__inner {
  transition: all 0.3s;
}

.el-input__inner:focus {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  border-color: #409eff;
}

.login-button {
  width: 100%;
  background-color: #409eff;
  border-color: #409eff;
  transition: all 0.3s;
}

.login-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
.register-link {
  text-align: center;
  margin-top: 15px;
}
</style>

